package main

import (
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"strings"
)

//使用go自带的http包实现方式1
func main() {
	//设置路由
	http.HandleFunc("/", sayHello)
	http.HandleFunc("/login", login)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}
func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()                      //解释参数，默认不会解释
	fmt.Println("method = ", r.Method) //获取请求方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("../static/htm/login.html")
		log.Println(t.Execute(w, nil))
	} else if r.Method == "POST" {
		//处理的是登陆请求
		// r.Form["usernaem"](0) 该方式要设置 r.ParseForm()
		// r.Form.Get("username") 该方式要设置 r.ParseForm()
		uname := r.FormValue("username")
		pword := r.Form.Get("password")
		fmt.Println("username:", uname)
		fmt.Println("password:", pword)
		fmt.Fprintf(w, "Login success, welcome "+uname) //这个写入到w的是输出到客户端的
	} else {
		fmt.Fprintf(w, "请先登陆...") //这个写入到w的是输出到客户端的
	}
}
func sayHello(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解释参数，默认不会解释
	fmt.Println(r.Form)
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Println("key", k)
		fmt.Println("value", strings.Join(v, ""))
	}
	io.WriteString(w, "Hello WebApp !!!")
}
